import sys
sys.path.append("/home/sshadmin/workspace/trilolo")
from logger import log
from database.interface import DBI
import json
import traceback
from datetime import datetime
from globals.ErrorClasses import AuthenticationError
from flask import render_template
from flask import g
from flask import make_response
import uuid
import urllib
from flask import request,redirect
import cgi
import hashlib

# Constants
import random
class Controller:
    def __init__(self,user_id=None,facebook_id=None,facebook_code=None):
        self.db=DBI()
        self.user=None
        self.first_run=False
        if facebook_id:
            self.user=self.db.getUser(facebook_id)
        elif facebook_code:
            self.register(facebook_code)
        elif user_id:
            self.user=self.db.getUser(user_id)
        if not self.user:
            log.debug("no user found , will create one")
            self.first_run=True
            self.register()
        else:
            log.debug(" user found "+ str(self.user.user_id))
    def register(self,facebook_code=None):
        if facebook_code:
            args = dict(client_id='158218584351709', redirect_uri="http://www.trilolo.com/")
            """redirect_url points to */login* URL of our app"""
            args["client_secret"] = '96bdef0cced3d721ea8b4c4f86a6450c'  #facebook APP Secret
            args["code"] = request.args.get("code")
            response = cgi.parse_qs(urllib.urlopen( "https://graph.facebook.com/oauth/access_token?" + urllib.urlencode(args)).read())
            log.debug("https://graph.facebook.com/oauth/access_token?" +
            urllib.urlencode(args))
            access_token = response["access_token"][-1]
            profile = json.load(urllib.urlopen("https://graph.facebook.com/me?" +urllib.urlencode(dict(access_token=access_token))))
            log.debug("profile "+str(profile))
            self.user=self.db.saveUser( created=datetime.now(),user_id=profile["id"],name=profile["name"],access_token=access_token,profile_url=profile["link"],facebook=1)
        else:
            user_id=str(uuid.uuid4())
            self.user=self.db.saveUser( created=datetime.now(),user_id=user_id,facebook=0,name=None,access_token=None,profile_url=None)
    def getSoundCloudTracks(self):
        history=self.db.userHistory(user=self.user)
        response=json.load(urllib.urlopen("https://graph.facebook.com/"+self.user.user_id+"/home?filter=app_19507961798&access_token="+self.user.access_token))
        data=response['data']
        log.debug("data "+str(data))
        links=[]
        for track in data:
            try:
                log.debug(track)
                log.debug(track['link'])
                links.append(track['link'])
                log.debug("link found soundcloud "+track['link'])
            except:
                log.error(traceback.format_exc())
        play_urls=[]
        for link in links:
            tmpd=dict()
            response=json.load(urllib.urlopen("http://api.soundcloud.com/resolve.json?url="+link+"&client_id=fa42787d4bb577572d0994e22e8bfd13"))
            tmp="http://api.soundcloud.com/tracks/"+str(response['id'])+"/stream/?client_id=fa42787d4bb577572d0994e22e8bfd13&format=json&callback="
            tmp=urllib.urlopen(tmp)
            tmpd['play_url']=tmp.geturl()
            tmpd['id']=hashlib.md5(link).hexdigest()
            if tmpd['id'] not in history: 
                play_urls.append(tmpd)
            else:
                log.debug(tmpd['id']+"in history")
            
        return play_urls    
            
    def logTrack(self,track=None,action=None,position=None,show=None):
        self.db.addTrackLog(user=self.user,track=track,action=action,position=position,show=show)    
    def getTopArtistsTracks(self):
        topArtists=self.db.getTopArtists()
        tracks=self.db.getTracksbyArtists(topArtists)
        history=self.db.userHistory(user=self.user)
        play_urls=[]
        for track in tracks:
            tmpd=dict()
            tmpd['play_url']=track.play_url
            tmpd['id']=track.md5
            if tmpd['id'] not in history: 
                play_urls.append(tmpd)
            else:
                log.debug(tmpd['id']+"in history")
        return play_urls
            
            
    def getOnetrack(self):
        collection=self.db.getTrack()
        tracks=[]
        history=self.db.userHistory(user=self.user)
        log.debug(history)
        for i in range(10):
            tmp=dict()
            r=random.randint(0,399)
            tmp['play_url']=collection[r].play_url
            tmp['id']=collection[r].md5
            if tmp['id'] not in history: 
                tracks.append(tmp)
            else:
                log.debug(tmp['id']+"in history")
        topArtistsTracks=self.getTopArtistsTracks()
        tracks.extend(topArtistsTracks)
        if self.user.facebook==1:  
            pass      
#             tracks_soundcloud=self.getSoundCloudTracks()
#             tracks.extend(tracks_soundcloud)
        #self.db.addRequest(user=self.user,track=tracks[r],action="track request")
        return tracks
                     
    def getTrack(self,track,show):
        if show :
            log.debug("it's a radio show")
            list,show_name=self.db.get_show(show)
            self.logTrack(action="page open",show=show)
            resp = make_response(render_template('index.html',play_url= list[0]['play_url'],user_id=self.user.name,id=list[0]['id'],list=list,first_run=self.first_run,show_name=show_name))
            if self.user.facebook==1:
                resp.set_cookie('facebook_id', self.user.user_id,max_age=30758400)
            else:
                resp.set_cookie('user_id', self.user.user_id,max_age=30758400)
            return resp
        if track:
            t=self.db.getTrackById(track)
        else:
            tracks=self.db.getTrack()
            r=random.randint(0,399)
            t=tracks[r]
        temp=dict()
        temp['id']=t.id
        temp['play_url']=t.play_url
        self.db.addRequest(user=self.user,track=t,action="page open")
        self.logTrack(track=t.md5,action="page open",position="None")
        list=self.getOnetrack()
        list.append(temp)
        resp = make_response(render_template('index.html',play_url= t.play_url,user_id=self.user.name,id=t.md5,list=list,first_run=self.first_run))
        if self.user.facebook==1:
            resp.set_cookie('facebook_id', self.user.user_id,max_age=30758400)
        else:
            resp.set_cookie('user_id', self.user.user_id,max_age=30758400)
        return resp
    def logout(self):
        resp = make_response()
        resp.set_cookie('facebook_id', self.user.user_id,max_age=0)
        return resp
    def login(self,user_id,facebook_id):
        if not facebook_id and user_id:
            args = dict(client_id='158218584351709', redirect_uri="http://www.trilolo.com/")
            log.debug("will login")
            log.debug("https://graph.facebook.com/oauth/authorize?" + urllib.urlencode(args))
            redirect("https://graph.facebook.com/oauth/authorize?" + urllib.urlencode(args))